<!-- TemplateList.vue -->
<template>
  <div>
    <div class="van-nav-bar--fixed px-15 !top-46 bg-black z-1 w-full">
      <NormalTabs
        :tabs="categoryInfoList"
        :active-id="categoryInfoId"
        :tab-class="tabClass"
        @update:active-id="categoryInfoId = $event"
      />
    </div>
    <div class="px-15 pt-55">
      <!-- 瀑布流组件 -->
      <Waterfall
        :templateInfoList="templateInfoList"
        :loading="loading"
        @load-more="loadMore"
        @item-click="handleItemSelection"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import NormalTabs from "@/components/NormalTabs/index.vue";
import { CategoryInfoData, categoryList } from "@/api/Home";
import { computed, onMounted, ref, watch, nextTick } from "vue";
import { useRoute } from "vue-router";
import setPageTitle from "@/utils/set-page-title";
import { TemplateInfoData, templateList } from "@/api/TemplateList";
import type { PageResponse } from "@/types";
import router from "@/router";

defineOptions({
  name: "TemplateList"
});
// 样式配置
const tabClass = ref({
  activeColor: "text-white",
  textColor: "text-999999"
});

const route = useRoute();

// 直接使用计算属性获取参数
const receivedId = ref(route.params.id as string);
const receivedName = ref(route.params.name as string);

// 分类请求列表
const categoryInfoList = ref<CategoryInfoData[]>([]);
const categoryInfoId = ref<string>("");

// 分类请求接口
const categoryListPort = async () => {
  const categoryRequestParam = { pid: receivedId.value };
  categoryInfoList.value = await categoryList(categoryRequestParam);
  categoryInfoList.value.unshift({
    contentList: [],
    cover: "",
    id: receivedId.value,
    name: "全部",
    pid: "0",
    sort: 0,
    status: 0
  });
  if (categoryInfoList.value.length) {
    categoryInfoId.value = categoryInfoList.value[0].id;
  }
};
// 计算属性：当 categoryInfoId 变化时，自动匹配 categoryInfoList 中的对应对象
const selectedCategory = computed(() => {
  if (!categoryInfoId.value) return null;
  return (
    categoryInfoList.value.find(item => item.id === categoryInfoId.value) ||
    null
  );
});

// 添加加载状态
const loading = ref(false);

// 加载更多方法
const loadMore = async () => {
  if (
    loading.value ||
    templateInfoList.value.current >= templateInfoList.value.pages
  )
    return;

  loading.value = true;
  try {
    const nextPage = templateInfoList.value.current + 1;
    const templateRequestParam: pageRequestParam = {
      categoryId: selectedCategory.value.id,
      pageNo: nextPage,
      pageSize: 20,
      pid: selectedCategory.value.pid
    };

    const result = await templateList(templateRequestParam);
    // 合并记录
    templateInfoList.value = {
      ...result,
      records: [...templateInfoList.value.records, ...result.records]
    };
  } finally {
    loading.value = false;
  }
};

// 分类请求参数
interface pageRequestParam {
  categoryId: string;
  pageNo: number;
  pageSize: number;
  pid: string;
}
// 分类请求列表
const templateInfoList = ref<PageResponse<TemplateInfoData>>({
  current: 1,
  pages: 0,
  records: [],
  size: 24,
  total: 0
});

// 修改模板请求接口，支持分页
const templateListPort = async (pageNo = 1) => {
  loading.value = true;
  try {
    const templateRequestParam: pageRequestParam = {
      categoryId: selectedCategory.value.id,
      pageNo: pageNo,
      pageSize: 20,
      pid: selectedCategory.value.pid
    };

    templateInfoList.value = await templateList(templateRequestParam);
  } finally {
    loading.value = false;
  }
};

// 监听分类ID变化，重新加载数据
watch(categoryInfoId, (newVal, oldVal) => {
  // 只有在分类确实变化时才滚动到顶部
  if (newVal !== oldVal) {
    // 使用nextTick确保DOM更新完成后再滚动
    nextTick(() => {
      // 直接滚动到页面顶部
      window.scrollTo({
        top: 0,
        behavior: "smooth"
      });
    });
  }

  // 重新加载数据
  templateListPort(1);
});

// 更新页面和导航栏标题
const updatePageTitle = () => {
  if (receivedName.value) {
    // 1. 设置浏览器标签标题
    setPageTitle(receivedName.value);
    // 2. 更新路由meta.title（导航栏会读取这个值）
    route.meta.title = receivedName.value;
  }
};

// 监听路由参数变化
watch(
  () => route.params,
  newParams => {
    if (newParams.name) {
      receivedName.value = newParams.name as string;
      updatePageTitle();
    }
    if (newParams.id) {
      receivedId.value = newParams.id as string;
      categoryListPort();
    }
  },
  { immediate: true }
);
// 监听模板选择
const handleItemSelection = (item: TemplateInfoData) => {
  navigateTo("TempleVideo", item);
};
// 跳转页面
const navigateTo = (routeName: string, params: TemplateInfoData) => {
  router.push({
    name: routeName,
    params: { id: params.id, name: params.name }
  });
};

onMounted(() => {
  // 确保初始加载时也设置标题
  if (receivedName.value) {
    updatePageTitle();
  }
});
</script>
<style scoped></style>
